package com.sh.demo.test;


import com.sh.demo.common.util.ShiroUtils;
import com.sh.demo.core.entity.SysUserEntity;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.Map;


@CrossOrigin
@Controller
public class Login {


    @GetMapping(value = "/login")
    public Object login(){
        ModelAndView m=new ModelAndView("/kk/login.html");
        return m;
    }


    /**
     * 登录
     */
    @PostMapping("/loginin")
    @ResponseBody
    public Object login( SysUserEntity sysUserEntity){
        Map<String,Object> map = new HashMap<>();
        //进行身份验证
        try{
            //验证身份和登陆
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(sysUserEntity.getUsername(), sysUserEntity.getPassword());
            //进行登录操作
            subject.login(token);
        }catch (IncorrectCredentialsException e) {
            map.put("code",500);
            map.put("msg","用户不存在或者密码错误");
            return map;
        } catch (LockedAccountException e) {
            map.put("code",500);
            map.put("msg","登录失败，该用户已被冻结");
            return map;
        } catch (AuthenticationException e) {
            map.put("code",500);
            map.put("msg","该用户不存在");
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            map.put("code",500);
            map.put("msg","未知异常");
            return map;
        }
//        map.put("code",0);
//        map.put("msg","登录成功");
//        map.put("token", ShiroUtils.getSession().getId().toString());
//        return map;
        return new ModelAndView("/kk/home.html");
    }



    @GetMapping("/ttt")
    public Object f(){
        ModelAndView m=new ModelAndView("/kk/ttt.html");
        return m;
    }



    @GetMapping("/testajax")
    @ResponseBody
    public Object f1(){

        Map map=new HashMap();
        map.put("code","200");
        map.put("msg","过了");
        return map;
    }


}
